package cn.rengy.web.framework.sys.pub.upload.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Callable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections4.MapUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import cn.rengy.lang.BusinessException;
import cn.rengy.lang.ResultEntity;
import cn.rengy.tool.core.PathBuilder;
import cn.rengy.tool.core.util.ExceptionPrintUtils;
import cn.rengy.tool.core.util._NumberUtils;
import cn.rengy.tool.image.ImageUtils;
import cn.rengy.tool.web._WebUtils;
import cn.rengy.tpa.wxmp.material.TempMediaApi;
import cn.rengy.tpa.wxmp.token.AccessToken;
import cn.rengy.web.framework.cache.CacheService;
import cn.rengy.web.framework.id.IdGenerator;
import cn.rengy.web.framework.property.service.PropertyService;
import cn.rengy.web.framework.sql.DbService;
import cn.rengy.web.framework.sys.pub.upload.SysPubFile;
import cn.rengy.web.framework.sys.pub.upload.SysPubFileInfo;
import cn.rengy.web.framework.util.GetSessionUtils;
import cn.rengy.web.framework.wxmp.token.AccessTokenCacheService;

@Service
public class PubFileService {
	@Autowired
	private DbService dbService;
	@Autowired
	private CacheService cacheService;
	@Autowired
	private IdGenerator idGenerator;
	@Autowired
	private PropertyService propertyService;
	private static Logger logger = LoggerFactory.getLogger(PubFileService.class);
	@Autowired
	private AccessTokenCacheService accessTokenCacheService;
	
	private Long tmpFileId=20862067816792064L;
	/**
	 * 得到文件表信息
	 * @param pub_file_id
	 * @return
	 */
	public SysPubFileInfo getPubFile(Long pub_file_id){
		String key=pub_file_id.toString();
		return cacheService.getLocalCache("pubfileCache", key, new Callable<SysPubFileInfo>() {
	        @Override
	        public SysPubFileInfo call() throws Exception {
	        	return dbService.queryForBean("select_get_pub_file",SysPubFileInfo.class, pub_file_id);
	        }
	    });
	}
	/**
	 * 得到保存路径
	 * @param pub_file_id
	 * @return
	 * @throws Exception 
	 */
	public File getSaveDir(SysPubFileInfo pubFile) {
		File targetDir=null;
		//String file_type=(String)pubFile.get("file_type");
		Integer is_public=pubFile.getIs_public();
		String uppath=null;//文件保存目录
		if(is_public!=null&&is_public==1) {
			uppath=this.propertyService.getProperty("UPLOAD_FILE_SAVE_PATH");
		}else {
			uppath=this.propertyService.getProperty("FILE_PRIVATE_STORE_PATH");
		}
		if(StringUtils.isBlank(uppath)) {
			throw new BusinessException("文件保存配置项为空");
		}
		
		PathBuilder path=new PathBuilder(uppath);
		String dir=pubFile.getSave_path();
		/*if("image".equals(file_type)){
			
		}else if("file".equals(file_type)){
			
		}*/
		if(StringUtils.isNotBlank(dir)){
			path.append(dir);
		}
		targetDir=new File(path.toString());
		if(!targetDir.exists()){
			targetDir.mkdirs();
		}
		return targetDir;
	}
	
	/**
	 * 微信临时素材
	 * @param paramMap
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public Map<String,Object> wxTempMedia(Map<String,Object> paramMap) throws ClientProtocolException, IOException {
		Map<String,Object> result=null;
		String media_id=(String)paramMap.get("media_id");
		Long file_id=MapUtils.getLong(paramMap, "file_id");
		SysPubFileInfo pubFile= getPubFile(file_id);
		File savePath = this.getSaveDir(pubFile);
		String appid = propertyService.getProperty("DEFAULT_WX_APPID");
		AccessToken accessToken=accessTokenCacheService.getAccessToken(appid);
		File imgFile=TempMediaApi.get(accessToken, media_id,savePath);
		result= this.uploaded(pubFile,paramMap, imgFile);
		return result;
	}
	/*public static final int BUFFER_SIZE = 4096;
	File targetFile=null;
	FileOutputStream out=null;
	if(in!=null) {
		
		try {
			byte[] head=new byte[4];
			in.read(head);
			String newFileName = UUID.randomUUID().toString().concat(".").concat(ImageTypeUtils.getFilePostfix(head));
			targetFile = new File(savePath ,newFileName);
			out=new FileOutputStream(targetFile);
			out.write(head);
			byte[] buffer = new byte[BUFFER_SIZE];
			int bytesRead = -1;
			while ((bytesRead = in.read(buffer)) != -1) {
				out.write(buffer, 0, bytesRead);
			}
			out.flush();
		}finally {
			try {
				in.close();
			}
			catch (IOException ex) {
			}
			try {
				out.close();
			}
			catch (IOException ex) {
			}
		}
	}*/
	/**
	 * 保存上传文件
	 * plupload碎片文件上传的原始文件名只能自定义参数上传
	 * @param request
	 * @throws IOException 
	 * @throws Exception
	 */
	@Transactional(rollbackFor=Exception.class)
	public Map<String,Object> upload(HttpServletRequest request) throws IOException {
		Map<String,Object> result=null;
		Map<String, Object> paras = new HashMap<String, Object>();
		logger.debug("request参数>>>>>>>>>>>>");
		for (Enumeration<String> eh = request.getParameterNames(); eh.hasMoreElements();){
			String parName = eh.nextElement();
			String parValue = request.getParameter(parName);
			paras.put(parName, parValue);
			logger.debug(parName+":"+request.getParameter(parName));
		}
		logger.debug("<<<<<<<<<<<<<<request参数");
		int chunks = _NumberUtils.toInt(paras.remove("chunks"), -1);// 获取总的碎片数
		
		int chunk = _NumberUtils.toInt(paras.remove("chunk"), -1);// 获取当前碎片计数(从0开始计数)
		
		String name = (String) paras.remove("name");// 文件名
		logger.debug("chunks={}" ,chunks);
		logger.debug("chunk={}" ,chunk);
		logger.debug("fileName={}" , name);//plupload碎片文件上传的时候生成的文件名
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultiValueMap<String, MultipartFile> map = multipartRequest.getMultiFileMap();
		/*logger.debug("------------------------");
		Iterator<String> iter = map.keySet().iterator();
		while (iter.hasNext()) {
			String key = iter.next();
			logger.debug(key);
		}
		logger.debug("--------------------");*/
		if (map != null) {
			// 事实上迭代器中只存在一个值,所以只需要返回一个值即可
			List<MultipartFile> fileList=map.entrySet().iterator().next().getValue();
			//List<MultipartFile> fileList = map.get("file");//plupload默认设置为file
			
			// for(MultipartFile multipartFile : fileList){
			MultipartFile multipartFile = fileList.get(0);
			//原始文件名，碎片上传模式为blob
			String originalFilename=multipartFile.getOriginalFilename();
			// 因为只存在一个值,所以最后返回的既是第一个也是最后一个值
			logger.debug("fileList.size=", fileList.size());
			logger.debug("getContentType=", multipartFile.getContentType());
			logger.debug("getName=" ,multipartFile.getName());
			logger.debug("getOriginalFilename=" , originalFilename);
			Long file_id=MapUtils.getLong(paras, "file_id");
			SysPubFileInfo pubFile= getPubFile(file_id);
			File savePath = this.getSaveDir(pubFile);

			// 上传的同时不能直接合并，原因：第一个碎片还没有写入，第二个碎片上传完成，文件被锁定，合并失败
			// 当chunks>1则说明当前传的文件为一块碎片，需要合并
			if (chunks > 1) {
				File chunkFile = new File(savePath, name + "_" + chunk);
				FileUtils.writeByteArrayToFile(chunkFile, multipartFile.getBytes());
				// FileUtils.writeByteArrayToFile(targetFile,
				// multipartFile.getBytes(),true);
				if (chunk == chunks - 1) {// 最后一块碎片，合并
					String newFileName = UUID.randomUUID().toString().concat(".")
							.concat(FilenameUtils.getExtension(name));
					File targetFile = new File(savePath,newFileName);
					// BufferedOutputStream outputStream = new
					// BufferedOutputStream(new FileOutputStream(targetFile));
					OutputStream out = FileUtils.openOutputStream(targetFile, true);
						// out.write(data);
					/* 遍历碎片文件 */
					for (int i = 0; i < chunks; i++) {
						File chunkFilei = new File(savePath, name + "_" + i);
						byte[] bytes = FileUtils.readFileToByteArray(chunkFilei);
						out.write(bytes);
						/*
						 * outputStream.write(bytes); outputStream.flush();
						 */
						chunkFilei.delete();
					}
					out.close();
					
					// 上传完成
					result= this.uploaded(pubFile,paras, targetFile);
					// outputStream.flush();
				}
			} else {// 没有碎片
				paras.put("original_file_name",originalFilename);
				//文件名取原始文件名
				//Map<String,Object> pubFile=this.getPubFile(paras.get("file_id"));
				String newFileName = UUID.randomUUID().toString().concat(".").concat(FilenameUtils.getExtension(originalFilename));
				File targetFile = new File(savePath ,newFileName);
				if(logger.isDebugEnabled()){
					String targetFilePath=targetFile.getPath();
					logger.debug("保存文件路径：{}",targetFilePath);
					logger.debug("保存文件路径是否绝对路径：{}",targetFile.isAbsolute());
				}
				multipartFile.transferTo(targetFile);
				// FileUtils.writeByteArrayToFile(targetFile,
				// multipartFile.getBytes());
				// 上传完成
				result= this.uploaded(pubFile,paras, targetFile);
			}
		}
		return result;
	}
	
	/**
	 * 文件上传后的处理
	 * @throws IOException 
	 */
	public Map<String,Object> uploaded(SysPubFileInfo pubFile,Map<String, Object> paras,File uploadFile) throws IOException {
		Map<String,Object> result=new HashMap<String,Object>(2);
		if(uploadFile!=null) {
			Long id=idGenerator.nextId();
			String accessUrl=null;
			Long user_id=GetSessionUtils.getUserId();
			//
			//Object target_id=paras.get("target_id");
			//Object file_type=paras.get("file_type");
			//Object original_file_name=paras.get("original_file_name");
			//Assert.hasLength(target_id, "target_id must not be null");
			//Integer multiple=(Integer)pubFile.get("multiple");
			String file_type=pubFile.getFile_type();//类型
			
			File newFile=null;
			String fileName=uploadFile.getName();
			paras.put("file_name",fileName);
			if("image".equals(file_type)){//图片
				//0不调整，1等比例调整，2按固定尺寸，3按宽等比例调整，4按高等比例调整
				Integer resize_type=pubFile.getResize_type();//是否缩略图
				Integer width=pubFile.getWidth();//(Integer)pubFile.get("width");//缩略图尺寸
				Integer height=pubFile.getHeight();//缩略图尺寸
				String filePath=uploadFile.getParent();
				String newFileName=fileName;
				if(resize_type==null||resize_type==0){//不调整尺寸
					newFile=uploadFile;
				}else{
					newFileName=UUID.randomUUID().toString()+"."+FilenameUtils.getExtension(fileName);
					newFile=new File(filePath,newFileName);
					if(resize_type==1){//等比例调整
						ImageUtils.zipRatio(uploadFile, newFile, width,height);
					}else if(resize_type==2){//固定尺寸调整
						ImageUtils.zipFixedSize(uploadFile, newFile, width,height);
					}else if(resize_type==3){//按宽等比例调整
						ImageUtils.zipByWidth(uploadFile, newFile,width);  
					}else if(resize_type==4){//按高等比例调整
						ImageUtils.zipByHeight(uploadFile, newFile,height);  
					}
					paras.put("file_name",newFileName);
					//删除旧图
					uploadFile.delete();
				}
				accessUrl=getAccessUrl(pubFile,newFileName);
				result.put("access_url", accessUrl);
				paras.put("access_url", accessUrl);
			}else if("file".equals(file_type)){//不需要做处理的文件
				newFile=uploadFile;
			}
			String store_type=pubFile.getStore_type();
			if(store_type.equals("disk")) {//保存在磁盘上
				paras.put("storage_path", newFile.getAbsolutePath());
				paras.put("file_type", file_type);
				paras.put("id", id);
				paras.put("creator_id", user_id);
				accessUrl=getFileAccessUrl(id);
				result.put("access_url", accessUrl);
				paras.put("access_url", accessUrl);
				this.dbService.updateMapParameter("insert_sys_pub_file_item", paras);
			}else{//保存在数据库
				String file_name=null;
				Object original_file_name=paras.get("original_file_name");
				String storage_path=null;
				long file_size=newFile.length();
				Date create_time=new Date();
				String access_url=null;
				Long company_id=null;
				byte file[]=FileUtils.readFileToByteArray(newFile);
				this.dbService.update("insert_sys_pub_file_item_blob",id, pubFile.getId(),file_type,file_name,original_file_name,storage_path,file_size,create_time,access_url,company_id,file);
				newFile.delete();
				
			}
			//返回结果
			result.put("item_id", id);
		}
		return result;
	}
	
	public String getAccessUrl(SysPubFileInfo pubFile,String filename) {
		String accesspath=this.propertyService.getProperty("IMAGE_ACCESS_PATH");//访问域名
		String path=pubFile.getSave_path();//保存相对路径
		PathBuilder pb=new PathBuilder(accesspath);
		return pb.append(path).append(filename).toString();
	}
	public String getFileAccessUrl(Long file_item_id){
		String domain=this.propertyService.getProperty("domain");
		String accesspath=this.propertyService.getProperty("FILE_ACCESS_PATH");//路径
		StringBuilder sb=new StringBuilder(domain);
		sb.append(accesspath).append(file_item_id);
		return sb.toString();
	}
	/**
	 * 删除单图item
	 */
	private void deleteFileitem(Object pub_file_id,Object target_id,String is_thumbnail){
		Map<String,Object> paramMap=new HashMap<String,Object>();
		paramMap.put("file_id", pub_file_id);
		paramMap.put("target_id", target_id);
		List<Map<String,Object>> fileItem=this.dbService.queryForListMapParameter("select_file_item_byfileidandtargetid", paramMap);
		if(fileItem!=null&&fileItem.size()>0){
			for(Map<String,Object> file:fileItem){
				String storage_path=(String)file.get("storage_path");
				Object id=file.get("id");
				this.dbService.updateBeanParameter("delete_file_item_byid", id);
				if("yes".equals(is_thumbnail)){
					String path=FilenameUtils.getFullPath(storage_path);
					String baseName=FilenameUtils.getBaseName(storage_path);
					String extension=FilenameUtils.getExtension(storage_path);
					File smallFile=new File(path+baseName+"-small."+extension);
					smallFile.delete();
				}
				File itemFile=new File(storage_path);
				itemFile.delete();
			}
		}
	}
	
	/**
	 * 更改删除状态
	 * @param paramMap
	 * @return
	 */
	public void delete(Map<String,Object> paramMap){
		List<Object> deletedRowIds=(List)paramMap.get("deletedRowIds");
		if(deletedRowIds!=null){
			Map<String,Object> deleteParam=new HashMap<String,Object>();
			deleteParam.put("ids", deletedRowIds);
			this.dbService.updateMapParameter("grid_sys_pub_file_item-delete", deleteParam);
		}
		
	}
	
	/**
	 * 删除已上传文件
	 */
	public void realDelete(Map<String,Object> paramMap){
		List<Object> deletedRowIds=(List)paramMap.get("deletedRowIds");
		if(deletedRowIds!=null){
			for(Object idobj:deletedRowIds){
				Long id=_NumberUtils.toLong(idobj, 0L);
				if(id!=0){
					Map<String,Object> item=this.dbService.queryForMap("select_get_sys_pub_file_item", id);
					String storage_path=(String)item.get("storage_path");
					File f=new File(storage_path);
					if(f.delete()){
						this.dbService.updateBeanParameter("grid_67_sys_pub_file_item-delete", id);
					}
				}
				
			}
		}
	}
	public void realDeleteById(Long id){
		if(id!=0){
			Map<String,Object> item=this.dbService.queryForMap("select_get_sys_pub_file_item", id);
			String storage_path=(String)item.get("storage_path");
			File f=new File(storage_path);
			if(f.delete()){
				this.dbService.updateBeanParameter("grid_67_sys_pub_file_item-delete", id);
			}
		}
	}
	/**
	 * 删除关系表
	 * @param paramMap
	 * @return
	 */
	public boolean deleterel(Map<String,Object> paramMap){
		Object id=paramMap.get("ids");
		this.dbService.updateBeanParameter("grid_sys_pub_file_item_target_rel-delete", id);
		return true;
	}
	public Map<String,Object> browse(Map<String,Object> paramMap){
		Map<String,Object> result=new HashMap<String,Object>();
		//file_id=:file_id and creator_id=:creator_id
		//Map<String,Object> select=new HashMap<String,Object>();
		//select.put("file_id", 3);
		List<Map<String,Object>> itemList=null;
		Long file_group_id=_NumberUtils.toLong(paramMap.get("file_group_id"), 0L);
		if(file_group_id==0){
			itemList=this.dbService.queryForListMapParameter("grid_sys_pub_file_item", paramMap);
		}else{
			itemList=this.dbService.queryForListMapParameter("select_file_item_by_groupid", paramMap);
		}
		if(itemList!=null){
			result.put("moveup_dir_path", "");
			result.put("current_dir_path", "");
			result.put("current_url", "");
			result.put("total_count", itemList.size());
			List<Map<String,Object>> fileList=new ArrayList<Map<String,Object>>(itemList.size());
			for(Map<String,Object> item:itemList){
				Map<String,Object> file=new HashMap<String,Object>();
				file.put("datetime", item.get("create_time"));
				file.put("filename", item.get("original_file_name"));
				file.put("access_url", item.get("access_url"));
				file.put("filesize", 0);
				file.put("filetype", "jpg");
				file.put("has_file", false);
				file.put("is_dir", false);
				file.put("is_photo", true);
				fileList.add(file);
			}
			result.put("file_list", fileList);
		}
		return result;
	}
	/**
	 * 单文件关系保存
	 * @param file_id
	 * @param tartget_id
	 */
	@Transactional
	public void saveSingle(Long file_id,Long tartget_id,Long file_item_id){
		if(file_id==null||file_id==0||tartget_id==null){
			throw new IllegalArgumentException("必要参数为空");
		}
		SysPubFileInfo pubFile= getPubFile(file_id);
		Integer is_share=pubFile.getIs_share();//是否与其他实例共享，是 不删除，否 删除文件
		//1.查询当前关联文件
		boolean is_insert=true;
		List<Map<String,Object>> fileList=this.dbService.queryForList("select_target_file_item", file_id,tartget_id);
		if(fileList!=null){
			for(Map<String,Object> f:fileList){
				String storage_path=(String)f.get("storage_path");
				String file_item_id0=MapUtils.getString(f, "file_item_id");
				String id=MapUtils.getString(f, "id");
				if(file_item_id!=null&&file_item_id.equals(file_item_id0)){
					is_insert=false;
				}else{//不是当前值,删除垃圾文件
					if(is_share!=null&&is_share==0) {//私有文件,更新以后删除旧文件
						if(StringUtils.isNotBlank(storage_path)) {
							File file=new File(storage_path);
							file.delete();
						}
						this.dbService.update("delete_file_item", file_item_id0);
						//删除关系表
						this.dbService.update("delete_sys_pub_file_item_target_rel", id);
					}
				}
			}
		}
		//3.新增关系表数据
		if(is_insert&&file_item_id!=null){
			Map<String,Object> insert=new HashMap<String,Object>(4,1);
			insert.put("file_item_id", file_item_id);//file_item_id,target_table,target_id
			insert.put("file_id", file_id);
			insert.put("target_id", tartget_id);
			insert.put("order_no", 0);
			//(file_item_id,file_id,target_id,order_no) values (:file_item_id,:file_id,:target_id,:order_no)
			this.dbService.updateMapParameter("insert_sys_pub_file_item_target_rel", insert);
		}
	}
	
	public List<Map<String,Object>> get(Long file_id,Long target_id){
		return this.dbService.queryForList("select_file_by_target", file_id,target_id);
	}
	/**
	 * 保存文件与目标关系
	 * @param file_id
	 * @param tartget_id
	 * @param file_item_ids
	 * @throws Exception 
	 */
	//@Transactional(rollbackFor = Exception.class,propagation=Propagation.NESTED)
	public void save(Long file_id,Long tartget_id,long... file_item_ids) throws Exception{
		if(file_id==null||file_id==0||tartget_id==null){
			throw new Exception("必要参数为空");
		}
		//TODO 校验file_item_ids都不为空不等于0
		if(file_item_ids!=null&&file_item_ids.length>0){
			//String ids[]=file_item_ids.split(",");
			Map<String, Object>[] batchValues=new Map[file_item_ids.length];
			for(int i=0;i<file_item_ids.length;i++){
				Long file_item_id=file_item_ids[i];
				batchValues[i]=new HashMap<String,Object>(4,1);
				batchValues[i].put("file_item_id", file_item_id);//file_item_id,target_tableinsert		batchValues[i].put("file_id", file_id);
				batchValues[i].put("file_id", file_id);
				batchValues[i].put("target_id", tartget_id);
				batchValues[i].put("order_no", i);
			}
			this.dbService.batchUpdate("insert_sys_pub_file_item_target_rel", batchValues);
		}
		/*//1.查询现有
		List<Map<String,Object>> imageList=this.dbService.queryListBySqlId("1", file_id,tartget_id);
		if(imageList==null||imageList.size()==0){//新增
			if(StringUtils.isNotBlank(file_item_ids)){//产品图片
				String ids[]=file_item_ids.split(",");
				Map<String, Object>[] batchValues=new Map[ids.length];
				for(int i=0;i<ids.length;i++){
					String file_item_id=ids[i];
					batchValues[i]=new HashMap<String,Object>(4);
					batchValues[i].put("file_item_id", file_item_id);//file_item_id,target_table,target_id
					batchValues[i].put("file_id", file_id);
					batchValues[i].put("target_id", tartget_id);
					batchValues[i].put("order_no", i);
				}
				this.dbService.batchUpdate("insert_sys_pub_file_item_target_rel", batchValues);
			}
		}else{//修改
			if(StringUtils.isNotBlank(file_item_ids)){//产品图片
				String ids[]=file_item_ids.split(",");
				
			}else{
				//删除全部
				
			}
		}*/
	}
	/**
	 * 保存生成的文件
	 * @param file_id
	 * @param tartget_id
	 * @param file_item_ids
	 * @throws Exception
	 */
//	@Transactional
//	public void saveFile(SysPubFileInfo pubFileInfo,File file,String tartget_id){
//		if(file==null||tartget_id==null){
//			throw new BusinessException("必要参数为空");
//		}
//		//新增文件
//		String file_item_id=idGenerator.generateId().toString();
//		SysPubFile sysPubFile=new SysPubFile();
//		sysPubFile.setId(file_item_id);
//		sysPubFile.setFile_id(pubFileInfo.getId());
//		sysPubFile.setFile_type(pubFileInfo.getFile_type());
//		sysPubFile.setFile_name(file.getName());
//		sysPubFile.setStorage_path(file.getAbsolutePath());
//		sysPubFile.setFile_size((int)file.length());
//		//sysPubFile.setCreate_time(create_time);
//		Long user_id=GetSessionUtils.getUserId();
//		sysPubFile.setCreator_id(user_id);
//		String access_url=getAccessUrl(pubFileInfo, file.getName());
//		sysPubFile.setAccess_url(access_url);
//		this.dbService.updateBeanParameter("insert_sys_pub_file_item", sysPubFile);
//		//1.新增关系表
//		Map<String, Object> insert=new HashMap<String,Object>(3,1);
//		insert.put("file_item_id", sysPubFile.getId());//file_item_id,target_table,target_id
//		insert.put("file_id", sysPubFile.getFile_id());
//		insert.put("target_id", tartget_id);
//		this.dbService.updateMapParameter("insert_sys_pub_file_item_target_rel", insert);
//	}
	
	/**
	 * 下载
	 * @param response
	 * @param file_item_id
	 * @throws IOException
	 * @throws FileNotFoundException
	 * @throws Exception
	 */
	public void download(HttpServletResponse response,String file_item_id) throws FileNotFoundException, IOException{
		Map<String,Object> file_item=this.dbService.queryForMap("select_get_sys_pub_file_item", file_item_id);
		String storage_path=(String)file_item.get("storage_path");
    	File file=new File(storage_path);
    	if(file.exists()){
    		String file_name=(String)file_item.get("original_file_name");
    		if(StringUtils.isBlank(file_name)) {
    			file_name=(String)file_item.get("file_name");
    		}
    		response.setContentType("application/octet-stream");
    		response.setContentLengthLong(file.length());
    		String filename=_WebUtils.urlEncode(file_name);
    		response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="+filename);
    		//response.setHeader(HttpHeaders.CACHE_CONTROL,  "no-cache");
    		//response.setHeader(HttpHeaders.CACHE_CONTROL,  "no-store");
    		FileCopyUtils.copy(new FileInputStream(file), response.getOutputStream());
    	}
	}
	
	public void download(HttpServletResponse response,Long file_id,Long target_id) throws FileNotFoundException, IOException{
		Map<String,Object> file_item=this.dbService.queryForMap("select_single_download_file_item", file_id,target_id);
		String storage_path=(String)file_item.get("storage_path");
    	File file=new File(storage_path);
    	if(file.exists()){
    		String file_name=(String)file_item.get("original_file_name");
    		if(StringUtils.isBlank(file_name)) {
    			file_name=(String)file_item.get("file_name");
    		}
    		response.setContentType("application/octet-stream");
    		response.setContentLengthLong(file.length());
    		String filename=_WebUtils.urlEncode(file_name);
    		response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="+filename);
    		//response.setHeader(HttpHeaders.CACHE_CONTROL,  "no-cache");
    		//response.setHeader(HttpHeaders.CACHE_CONTROL,  "no-store");
    		FileCopyUtils.copy(new FileInputStream(file), response.getOutputStream());
    	}else {
    		_WebUtils.responseWrite("文件未找到", response);
    	}
	}
	
	public ResultEntity<?> queryDownload(Long file_item_id){
		Map<String,Object> file_item=this.dbService.queryForMap("select_get_sys_pub_file_item", file_item_id);
		if(file_item==null) {
			return ResultEntity.fail();
		}else {
			return ResultEntity.ok(file_item.get("access_url"));
		}
	}
	
	/**
	 * 清空测试数据-文件,危险操作，测试环境执行
	 */
//	public void deleteTestData(){
//		try{
//			List<Map<String,Object>> list=this.dbService.queryForList("select_test_data_file");
//			if(list!=null&&list.size()>0){
//				for(Map<String,Object> file_item:list){
//					String storage_path=(String)file_item.get("storage_path");
//			    	File file=new File(storage_path);
//			    	if(file.exists()){
//			    		Object id=file_item.get("id");//itemid
//			    		//删除文件表
//			    		this.dbService.update("delete_temp_file", id);
//			    		file.delete();
//			    	}
//				}
//			}
//			//删除关系表
//    		this.dbService.update("delete_test_data_file_rel");
//		}catch(Exception e){
//			logger.error(ExceptionPrintUtils.getTrace(e));
//		}
//	}
	
}
